#include <iostream>
#include <sys/socket.h>
#include "../socks/sock.h"
#include "../socks/sockdist.h"

using namespace std;

int main(int argc, char** argv)
{
	if(argc > 1)
	{
		bool run = true;
		
		Sock maBR(SOCK_DGRAM, 0);
		
		int descBRLoc;
		
		if(maBR.good())
		{
			descBRLoc = maBR.getsDesc();
		}
		else
		{
			cout << "Error : BR" << endl;
			exit(1);
		}
		
		SockDist saBR(argv[1], (short)50001);
		sockaddr_in *adrsaBR = saBR.getAdrDist();
		
		char msg[1024];
		
		do
		{
			cout << "Entrer le message à envoyer (FIN pour arreter): ";
			cin.getline(msg, 1024);
			
			cout << "Message envoye : " << msg << endl;
				
			int retourSend = sendto(descBRLoc, msg, sizeof(msg), 0, (sockaddr*)adrsaBR, saBR.getsLen());
			
			if(msg[0] == 'F' && msg[1] == 'I' && msg[2] == 'N')
			{
				run = false;
			}
		
		
			if(run)
			{
				if(retourSend == -1)
				{
					cout << "Error : RetourSend" << endl;
				}
				else
				{
					char tmpRecv[1024];
					int lgRecv = 1024;
					
					cout << "Attente de message ... " << endl;
			
					
					int retourRecv = recvfrom(descBRLoc, tmpRecv, lgRecv, 0, NULL, NULL);
					
					if(retourRecv != -1)
					{
						cout << "Message recu : ";
						cout << tmpRecv << endl;
						
						if(tmpRecv[0] == 'F' && tmpRecv[1] == 'I' && tmpRecv[2] == 'N')
						{
							run = false;
						}
					}
					else
					{
						cout << "Error : retourRecv" << endl;
					}
					
					cout << endl;
				}
			}
		} while(run);
	}
	
	return 0;
}

 
